import { defineStore } from "pinia";
export interface NavTag {
  id: string;
  name: string;
  path: string;
}
export const useTagStore = defineStore("tag", () => {
  const navTags = ref<NavTag[]>([]);
  const currentNavTag = ref({} as NavTag);

  const getCurrentTag = computed(() => currentNavTag.value);

  const loadCurrentTag = () => {
    const currentTag = localStorage.getItem("currentTag");
    if (currentTag) {
      currentNavTag.value = JSON.parse(currentTag);
    }
  };

  const setCurrentTag = (navTagId: string) => {
    const tag = navTags.value.find((navTag) => navTag.id === navTagId);
    tag && (currentNavTag.value = tag);
  };

  const saveCurrentTags = () => {
    localStorage.setItem("currentTag", JSON.stringify(currentNavTag.value));
  };

  const getTags = computed(() => navTags.value);

  const loadTags = () => {
    const storedTags = localStorage.getItem("tags");
    if (storedTags) {
      navTags.value = JSON.parse(storedTags);
    }
  };
  const saveTags = () => {
    localStorage.setItem("tags", JSON.stringify(navTags.value));
  };
  const addTag = (tag: NavTag) => {
    const isRepeat = navTags.value.some((item) => item.id === tag.id);
    if (!isRepeat) {
      navTags.value.push(tag);
      return tag;
    }
  };
  const updateTag = (id: string, tag: MyPartial<NavTag>) => {
    const index = navTags.value.findIndex((item) => item.id === id);
    if (index !== -1) {
      navTags.value[index] = {
        ...navTags.value[index],
        ...tag,
      };
    }
  };
  const removeTag = (tagId: string) => {
    const index = navTags.value.findIndex((item) => item.id === tagId);
    navTags.value.splice(index, 1);
  };
  const delAllTags = () => {
    navTags.value = [];
  };
  const clearAllTags = () => {
    navTags.value = [];
  };
  loadTags();
  loadCurrentTag();

  watch(navTags, saveTags, { deep: true });
  watch(currentNavTag, saveCurrentTags, { deep: true });
  return {
    getTags,
    addTag,
    updateTag,
    removeTag,
    delAllTags,
    getCurrentTag,
    setCurrentTag,
    clearAllTags,
  };
});
